import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
from sklearn.model_selection import train_test_split
from keras.models import load_model
from matplotlib import pyplot as plt

plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams['axes.unicode_minus'] = False
np.random.seed(1986)

# 导入数据
data_source = pd.read_excel("糖尿病发病情况数据集.xlsx")
x = data_source[['怀孕次数', '血浆葡萄糖浓度', '舒张压', '三头肌皮褶皱厚度', '2小时血清胰岛素', '身体质量指数', '糖尿病谱系功能', '年龄']]
y = data_source['是否是糖尿病']
# 拆分训练集和测试集
(train_x, test_x, train_y, test_y) = train_test_split(
    x, y, train_size=0.8, test_size=0.2)

# 创建模型
model = Sequential()
model.add(Dense(units=128, input_dim=x.shape[1], activation='relu'))
model.add(Dense(units=64, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))

# 打印模型信息
model.summary()

# 编译模型
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

# 训练模型
# verbose: 0 = silent, 1 = progress bar, 2 = one line per epoch.
history = model.fit(train_x, train_y,
          epochs=500, batch_size=32, verbose=1)

# 绘制训练过程(准确度) 
plt.plot(history.history["acc"])
plt.title("模型准确度")
plt.xlabel("epoch")
plt.ylabel("accuracy")
plt.show()

# 绘制训练过程(损失函数)
plt.plot(history.history["loss"])
plt.title("模型损失函数")
plt.xlabel("epoch")
plt.ylabel("loss_value")
plt.show()

# 评估模型
scores = model.evaluate(train_x, train_y, verbose=0)
print("训练集,%s=%.2f" % (model.metrics_names[1], scores[1]))

scores = model.evaluate(test_x, test_y, verbose=0)
print("测试集,%s=%.2f" % (model.metrics_names[1], scores[1]))

# 保存模型 
model.save("二分类.h5")

# 加载模型
loaded_model = load_model("二分类.h5")
# 预测
predict_x = np.array([[1, 2, 3, 4, 5, 6, 7, 8], [1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1]])
# 类别
print(loaded_model.predict_classes(predict_x))
# 准确性
print(loaded_model.predict_proba(predict_x))

